package cn.rubintry.bug.hunting.room

import android.content.Context
import androidx.room.Room

class DbManager {

    private var appContext: Context ?= null

    private var db: AppDatabase ?= null

    fun init(context: Context){
        this.appContext = context.applicationContext
    }

    fun getDatabase(): AppDatabase {
        assert(appContext != null){"必须先init"}
        if(db == null){
            db = Room.databaseBuilder<AppDatabase>(
                appContext!!,
                AppDatabase::class.java,
                "BugHuntingDb"
            )
                .allowMainThreadQueries()
                .fallbackToDestructiveMigrationOnDowngrade()
                .build()
        }
        return db!!
    }

    companion object{
        @Volatile
        private var instance : DbManager ?= null
        @JvmStatic
        fun getInstance(): DbManager {
            if(null == instance){
                synchronized(DbManager::class.java){
                    if(null == instance){
                        instance = DbManager()
                    }
                }
            }
            return instance!!
        }
    }
}